package pl.com.qapps.datastore.berkeley;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public abstract class LazyIterableWrapper<W,T> implements Iterable<T> {

	private final Iterable<W> wrapped;
	private Iterable<T> ready;

	public LazyIterableWrapper(Iterable<W> wrapped) {
		super();
		this.wrapped = wrapped;
	}

	@Override
	public Iterator<T> iterator() {
		return ready != null ? ready.iterator() : new Iterator<T>() {

			private Iterator<W> iter = wrapped.iterator();
			private List<T> build = new LinkedList<>();

			@Override
			public boolean hasNext() {
				return iter.hasNext();
			}

			@Override
			public T next() {
				T wrapper = wrap(iter.next());
				build.add(wrapper);
				if (!iter.hasNext() && ready != null)
					ready = build;
				return wrapper;
			}

			@Override
			public void remove() {
				iter.remove();
				build.remove(build.size() - 1);
			}

		};
	}

	protected abstract T wrap(W item);

}
